import { login, getInfo } from '@/api/user'
import {
  setToken,
  removeToken,
  getToken,
  getTenantId,
  removeTenantId
} from '@/utils/auth'
import { Message } from 'element-ui'
const getDefaultState = () => {
  return {
    token: getToken() || '',
    user_id: getTenantId() || '',
    name: '',
    userInfo: {}
  }
}

const state = getDefaultState()

// 方法
const mutations = {
  // 登录
  SET_TOKEN: (state, token) => {
    setToken(token)
    state.token = token
  },
  SET_USERINFO: (state, Obj) => {
    state.userInfo = Obj
  },
  SET_USER_ID: (state, id) => {
    state.user = id
  },
  SET_NAME: (state, name) => {
    state.name = name
  }
}
// 请求
const actions = {
  // 登录
  async login (ctx, data) {
    const { username, password } = data
    let res = await login({ username: username.trim(), password: password })
    console.log(res)
    // 调用mutations里的方法存到state
    ctx.commit('SET_TOKEN', res.data.token)
  },
  // 用户信息
  // async getInfo ({ commit, state }) {
  //   // console.log('state.token', state.token)
  //   const { data: res } = await getInfo(state.token)
  //   console.log(res)
  //   const { name, avatar } = res
  //   // ctx.commit('SET_USERINFO', res.data)
  //   commit('SET_NAME', name)
  // },
  // 退出登录
  logout (ctx) {
    ctx.commit('SET_TOKEN', '')
    ctx.commit('SET_USER_ID', '')
    ctx.commit('SET_USERINFO', {})
    removeToken()
    removeTenantId()
    Message.success('退出成功，请重新登录')
  }
}

export default {
  // 开启私密空间
  namespaced: true,
  state,
  mutations,
  actions
}
